package com.wenhai.spring.dependency.injection;

import com.wenhai.spring.dependency.injection.annotation.InjectionUser;
import com.wenhai.xiaomage.spring.ioc.overview.dependency.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.springframework.context.annotation.AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME;

/**
 * @Author:wenhai
 * @Description: 注解方式字段依赖注入过程
 * @Date:2020/3/10
 */
public class AnnotationDependencyInjectionResolutionDemo {

    @Autowired
    private User user; // DependencyDescriptor->必须required=true + 实时 eager = true注入+通过类型(User.class)查找(处理)+字段名称("user")

    @Autowired
    private Map<String,User> users;

    @InjectionUser
    private User injectUser;

    private static final Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
    public static void main(String[] args) {


        AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext();
        cxt.register(AnnotationDependencyInjectionResolutionDemo.class);
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(cxt);
        String xmlResourcePath = "classpath:/META-INF/dependency-lookup-context.xml";
        beanDefinitionReader.loadBeanDefinitions(xmlResourcePath);
        cxt.refresh();
        AnnotationDependencyInjectionResolutionDemo demo = cxt.getBean(AnnotationDependencyInjectionResolutionDemo.class);
        System.out.println(demo.user);
        System.out.println(demo.users);
        System.out.println(demo.injectUser);
        cxt.close();

    }

    @Bean(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)
    public AutowiredAnnotationBeanPostProcessor beanFactory() {
        AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor = new AutowiredAnnotationBeanPostProcessor();
        autowiredAnnotationBeanPostProcessor.setAutowiredAnnotationType(InjectionUser.class);
        return autowiredAnnotationBeanPostProcessor;
    }
//    @Bean
//    @Order(Ordered.LOWEST_PRECEDENCE - 3)
//    public static AutowiredAnnotationBeanPostProcessor customAnnotation() {
//        AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor = new AutowiredAnnotationBeanPostProcessor();
//        autowiredAnnotationBeanPostProcessor.setAutowiredAnnotationType(InjectionUser.class);
//        return  autowiredAnnotationBeanPostProcessor;
//    }


    private static boolean isContainChinese(String str) {
        Matcher m = p.matcher(str);
        return m.find();
    }

}
